package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.comment.service.TextReviewsService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    TextReviewsService textReviewsService;
    @Autowired
    UserFeign userFeign;

    @Override
    public ResponseResult save(CommentRepaySaveDTO dto) {
        //校验用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //文本内容安全校验
        String textScan = textReviewsService.handleSensitive(dto.getContent());
        String textContent = textReviewsService.handleTextScan(textScan);
        //根据当前评论id查询评论数据
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询不到此条评论");
        }
        //远程查询当前登陆用户信息
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        user = result.getData();
        //保存回复信息至mongoDB
        ApCommentRepay apCommentRepay = ApCommentRepay.builder().authorId(user.getId())
                .authorName(user.getName()).commentId(dto.getCommentId())
                .content(textContent).likes(0).createdTime(new Date())
                .updatedTime(new Date()).build();
        mongoTemplate.save(apCommentRepay);
        //修改评论信息中回复+1
        mongoTemplate.updateFirst(query, new Update().set("reply", (apComment.getReply() + 1)), ApComment.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //校验用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录!");
        }
        //根据评论id查询评论数据
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论回复数据不存在");
        }
        Query query = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId())
                .and("authorId").is(user.getId()));
        Query CommentQuery = Query.query(Criteria.where("id").is(commentRepay.getId()));
        //查询是否有点赞数据
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);

        if (dto.getOperation() == 0) {
            if (commentRepayLike != null) {
                //已点赞
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
            }
            //未点赞,进行点赞保存数据到mongoDB
            ApCommentRepayLike apCommentRepayLike = ApCommentRepayLike.builder().commentRepayId(dto.getCommentRepayId()).authorId(user.getId())
                    .operation(dto.getOperation()).build();
            mongoTemplate.save(apCommentRepayLike);
            //更新评论的点赞数量
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);
        } else {
            //取消点赞操作
            if (commentRepayLike == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "您还没有点赞");
            }
            //删除点赞信息
            mongoTemplate.remove(query, ApCommentRepayLike.class);
            //修改评论信息的点赞数量 - 1
            commentRepay.setLikes(commentRepay.getLikes() < 0 ? 0 : commentRepay.getLikes() - 1);
            mongoTemplate.save(commentRepay);
            //更新 APP评论信息点赞
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        //创建返回数据map集合
        HashMap<String, Integer> map = new HashMap<>();
        map.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //校验size
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        //校验时间
        Date date = dto.getMinDate();
        if (dto.getMinDate() == null) {
            date = new Date();
        }
        //根据条件查询评论回复信息列表
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(date)).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(size);
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);

        //校验用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //未登录直接返回评论回复列表
            return ResponseResult.okResult(list);
        }
        //查询当前回复评论列表的id集合
        List<String> ids = list.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        //用户点赞的回复数据集合
        List<ApCommentRepayLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria.where("commentRepayId")
                .in(ids).and("authorId").is(user.getId())), ApCommentRepayLike.class);
        //获取点赞数据的回复评论id
        List<String> commentIds = apCommentLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());

        list.forEach(commentRepay -> {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(commentRepay, apCommentRepayVO);
            //如果当前回复评论的id在点赞记录中存在
            if (commentIds.contains(commentRepay.getId())) {
                apCommentRepayVO.setOperation((short) 0);
            }
        });
        return ResponseResult.okResult(list);
    }
}
